package com.jiazhong.cloud.governance.consumer.service.impl;

import com.jiazhong.cloud.governance.consumer.service.ConsumerService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@Slf4j
@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;


    @Override
    public String hello() {
        // 发现名称为 cloud-service-governance-provider 的微服务（集群）
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-service-governance-provider");
        log.info("集群的个数是：{}", instances.size());
        // 获取其中的一个
        ServiceInstance instance = instances.get(0);
        log.info("instance:{}", instance);
        // 调用
        String uri = instance.getUri().toString();
        log.info("需要访问的路径是：{}", uri);
        String result = restTemplate.getForObject(uri + "/provider", String.class);
        log.info("result:{}", result);
        return result;
    }

    private int i = 0;

    @Override
    public String helloAround() {
        // 发现名称为 cloud-service-governance-provider 的微服务（集群）
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-service-governance-provider");
        log.info("集群的个数是：{}", instances.size());
        // 获取其中的一个
        ServiceInstance instance = instances.get(i);
        if (i == instances.size() - 1) {
            i = 0;
        } else {
            i++;
        }
        log.info("instance:{}", instance);
        // 调用
        String uri = instance.getUri().toString();
        log.info("需要访问的路径是：{}", uri);
        String result = restTemplate.getForObject(uri + "/provider", String.class);
        log.info("result:{}", result);
        return result;
    }

    @Override
    public String helloRandom() {
        // 发现名称为 cloud-service-governance-provider 的微服务（集群）
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-service-governance-provider");
        log.info("集群的个数是：{}", instances.size());
        // 获取其中的一个
        int j = (int) (Math.random() * instances.size());
        ServiceInstance instance = instances.get(j);
        log.info("instance:{}", instance);
        // 调用
        String uri = instance.getUri().toString();
        log.info("需要访问的路径是：{}", uri);
        String result = restTemplate.getForObject(uri + "/provider", String.class);
        log.info("result:{}", result);
        return result;
    }
}
